package wechat.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import wechat.bean.WechatInformationBean;
import wechat.bean.response.EventMessageBean;
import wechat.bean.response.MessageBaseBean;
import wechat.bean.response.message.reply.ReplyImageTextItemBean;
import wechat.dao.EventDao;
import wechat.dao.MessageDao;
import wechat.dao.SubscribeInfoDao;
import wechat.entity.EventEntity;
import wechat.entity.MessageEntity;
import wechat.entity.SubscribeInfoEntity;
import wechat.resources.InstanceResource;
import wechat.response.business.event.message.SubscribeEventBusiness;
import wechat.service.WechatInfoService;
import wechat.util.StreamUtil;
import wechat.util.WechatUtil;
import wechat.util.aes.AesException;
import wechat.util.aes.WXBizMsgCrypt;

@Service
public class IWechatInfoService implements WechatInfoService {
	
	private Logger log = LoggerFactory.getLogger(IWechatInfoService.class);	
	
	
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private EventDao eventDao;
	@Autowired
	private SubscribeInfoDao subscribeInfoDao;
	
	public String doWechatInfo(InstanceResource instanceResource,WechatInformationBean wechatInformationBean){
//		<xml><ToUserName><![CDATA[wxd68e32bf259a2fb4]]></ToUserName>
//		<FromUserName><![CDATA[zhang]]></FromUserName>
//		<CreateTime>1476755150</CreateTime>
//		<MsgType><![CDATA[text]]></MsgType>
//		<Content><![CDATA[1]]></Content>
//		<MsgId>3685823964297860752</MsgId>
//		<AgentID>53</AgentID>
//		</xml>
	
//		<xml><ToUserName><![CDATA[wxd68e32bf259a2fb4]]></ToUserName>
//		<FromUserName><![CDATA[570ebbdb99da181b646b0ccec63dc9eb]]></FromUserName>
//		<CreateTime>1476757543</CreateTime>
//		<MsgType><![CDATA[event]]></MsgType>
//		<AgentID>53</AgentID>
//		<Event><![CDATA[view]]></Event>
//		<EventKey><![CDATA[https://www.baidu.com/]]></EventKey>
//		</xml>
		
		
		String respResult = "success";
		try {

			String msgSignature = wechatInformationBean.getMsgSignature();
			String timestamp = wechatInformationBean.getTimestamp();
			String nonce = wechatInformationBean.getNonce();
			InputStream input = wechatInformationBean.getDataInputStream();
			
			WXBizMsgCrypt wxBizMsgCrypt = instanceResource.getWXBizMsgCrypt();
			
			String str = StreamUtil.inputStreamToString(input);
			
			log.info("IWechatInfoService--doWechatInfo  str=" + str);

			wxBizMsgCrypt = instanceResource.getWXBizMsgCrypt();
			
			String info = wxBizMsgCrypt.decryptMsg(msgSignature, timestamp, nonce, str);
			log.info("IWechatInfoService -- doWechatInfo info=" + info);
			
			respResult = execute(instanceResource,info);
			
			timestamp = String.valueOf(System.currentTimeMillis());
			nonce = WechatUtil.getNonceStr();
			String encryptMsg = wxBizMsgCrypt.encryptMsg(respResult, timestamp, nonce);

			log.info("IWechatInfoService -- doWechatInfo   encryptMsg=" + encryptMsg);
			
			
			return encryptMsg;
			
		}  catch (AesException e) {
			log.error("doWechatInfo -- message: 文本解密失败！", e);
			e.printStackTrace();
		}  catch (Exception e) {
			log.error("doWechatInfo -- message: Fail！", e);
			e.printStackTrace();
		}
		
		return respResult;
	}
	
	
	public List<MessageEntity> findMessage() {
		return messageDao.getMessage();
	}
	
	public List<EventEntity> findEvent() {
		return eventDao.getEvent();
	}
	
	private String execute(InstanceResource instanceResource,String info) throws Exception{
		MessageBaseBean messageBaseBean = new MessageBaseBean(info);
		messageBaseBean.transform();

		String result = "success";
		
		String msgType = messageBaseBean.getMsgType();
		
		if (msgType == null) {
			log.info("IWechatInfoService -- execute  messageBaseBean=" + messageBaseBean);
			return result;
		}
		
		String toUserName = messageBaseBean.getToUserName();
		String fromUserName= messageBaseBean.getFromUserName();
		String msgId= messageBaseBean.getMsgId();
		String agentID= messageBaseBean.getAgentID();
		String originInfo= info;
		Date createTime= new Date();
		
		if (msgType.equals(MessageBaseBean.Message_Event)) {
			EventMessageBean eventMessageBean = new EventMessageBean(info);
			eventMessageBean.transform();
			
			String respEvent = eventMessageBean.getEvent();
			EventEntity eventEntity = new EventEntity();
			eventEntity.setToUserName(toUserName);
			eventEntity.setFromUserName(fromUserName);
			eventEntity.setEvent(respEvent);
			eventEntity.setMsgType(msgType);
			eventEntity.setAgentID(agentID);
			eventEntity.setCreateTime(createTime);
			eventEntity.setOriginInfo(originInfo);
			
			eventDao.addEvent(eventEntity);
			
			
			String respEventKey = eventMessageBean.getEventKey();
			result = doPassiveResponseForEvent(instanceResource,info,respEvent, respEventKey);
			
			
		} else {
			
			MessageEntity messageEntity = new MessageEntity();
			
			messageEntity.setToUserName(toUserName);
			messageEntity.setFromUserName(fromUserName);
			messageEntity.setMsgId(msgId);
			messageEntity.setMsgType(msgType);
			messageEntity.setAgentID(agentID);
			messageEntity.setCreateTime(createTime);
			messageEntity.setOriginInfo(originInfo);
			
			messageDao.addMessage(messageEntity);
			
			
			result = doPassiveResponseForMessage(instanceResource,info,msgType);
			
		}
		
		return result;
	}
	
	
	private String doPassiveResponseForEvent(InstanceResource instanceResource,String info,String respEvent,String respEventKey) throws Exception{
		String result = "success";
		if (respEvent.equals(MessageBaseBean.Event_Subscribe)) {
			SubscribeEventBusiness subscribeEventBusiness = new SubscribeEventBusiness(instanceResource, info);
			
			SubscribeInfoEntity subscribeInfoEntity = subscribeInfoDao.getSubscribeInfo();
			
			List<ReplyImageTextItemBean> articles = new ArrayList<ReplyImageTextItemBean>();
			
			ReplyImageTextItemBean replyImageTextItemBean = new ReplyImageTextItemBean();
			replyImageTextItemBean.setTitle(subscribeInfoEntity.getTitle());
			replyImageTextItemBean.setDescription(subscribeInfoEntity.getDescription());
			replyImageTextItemBean.setPicUrl(subscribeInfoEntity.getPicUrl());
			replyImageTextItemBean.setUrl(subscribeInfoEntity.getUrl());
			
			articles.add(replyImageTextItemBean);
			
			result = subscribeEventBusiness.getReplyNews(articles);
		}
//		else if (respEvent.equals(MessageBaseBean.Event_ScancodeWaitmsg)) {
//
//		}
		
		return result;
	}
	
	private String doPassiveResponseForMessage(InstanceResource instanceResource,String info,String msgType) throws Exception {
		String result = "success";
		//暂时不处理信息响应
//		if (msgType.equals(MessageBaseBean.Receive_Message_Text)) {	
//
//		}
		
		
		return result;
	}


	
}
